#!/usr/bin/python
#coding=utf-8

from web.response import Response
from dbutils import DBUtils
import MySQLdb
from MySQLdb.cursors import DictCursor
import datetime
from igor import logging

def application(environ, start_response):
    resp = Response(start_response)
    clean()
    return resp.respond()

def clean():
    dbutils, conn, cur = DBUtils(), None, None
    sql = """
        SELECT bid, expire, bdate FROM bankorder WHERE status=0
    """
    sql_delete = """
        DELETE FROM bankorder WHERE bid=%s
    """
    try:
        rows = dbutils.execute_dict(sql)
        todelete = []
        for row in rows:
            bid, expire, bdate = row['bid'], row['expire'], row['bdate']
            expire_time = datetime.datetime.now() - datetime.timedelta(seconds=expire)
            expire_time = expire_time.strftime('%Y-%m-%d %H:%M:%S')
            if str(bdate) < expire_time:
                todelete.append(bid)
        conn = dbutils.connect()
        cur = conn.cursor(DictCursor)
        logging.log('clean expired orders, number=%s' % len(todelete))
        cur.executemany(sql_delete, todelete)
        conn.commit()
    except MySQLdb.Error, err:
        logging.log(err)
    finally:
        dbutils.close(conn, cur)

if __name__ == '__main__':
    clean()
